/*
 *  GameApp.cpp
 *  SimpleShmup
 *
 *  Created by William on 8/10/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include "GameApp.h"

#include "SDL.h"
#include "Player.h"

using namespace std;

/**
 * I'm still curious why this line is needed to avoid build failed:
 * "GameApp::instance", referenced from:
 * __ZN7GameApp8instanceE$non_lazy_ptr in GameApp.o symbol(s) not found
 * error.
 */
GameApp *GameApp::instance = 0;

GameApp *GameApp::getInstance() {
	if (!instance) {
		instance = new GameApp();
	}
	
	return instance;
}

GameApp::GameApp() :
screen(0) 
{
	Uint32 initflags = SDL_INIT_EVERYTHING;  /* See documentation for details */
	Uint8  video_bpp = 32;
	Uint32 videoflags = SDL_SWSURFACE;
	
	/* Initialize the SDL library */
	if ( SDL_Init(initflags) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",
				SDL_GetError());
		exit(1);
	}
	
	/* Set 640x480 video mode */
	screen = SDL_SetVideoMode(640,480, video_bpp, videoflags);
	if (screen == NULL) {
		fprintf(stderr, "Couldn't set 640x480x%d video mode: %s\n",
				video_bpp, SDL_GetError());
		SDL_Quit();
		exit(2);
	}
}

GameApp::~GameApp() {
	// clean up the SDL library
	SDL_Quit();
}

void GameApp::start() {
	SDL_Event event;
	
	Player *player = new Player();
	
	int done = 0;
	while ( !done ) {
		
		/* Check for events */
		while ( SDL_PollEvent(&event) ) {
			switch (event.type) {
					
				case SDL_MOUSEMOTION:
					break;
				case SDL_MOUSEBUTTONDOWN:
					break;
				case SDL_KEYDOWN:
					switch (event.key.keysym.sym) {
						case SDLK_LEFT:
							player->moveLeft(true);
							break;
						case SDLK_RIGHT:
							player->moveRight(true);
							break;
						case SDLK_UP:
							player->moveUp(true);
							break;
						case SDLK_DOWN:
							player->moveDown(true);
							break;
						default:
							break;
					}
					break;
				case SDL_KEYUP:
					switch (event.key.keysym.sym) {
						case SDLK_LEFT:
							player->moveLeft(false);
							break;
						case SDLK_RIGHT:
							player->moveRight(false);
							break;
						case SDLK_UP:
							player->moveUp(false);
							break;
						case SDLK_DOWN:
							player->moveDown(false);
							break;
						default:
							break;
					}
					break;
				case SDL_QUIT:
					done = 1;
					break;
				default:
					break;
			}
		}
		
		SDL_FillRect(screen, NULL, 0);
		
		player->tick();
		player->draw(screen);
		
		SDL_Flip(screen);
	}
}
